package com.anxin.baseproject2.rx;


import com.anxin.baseproject2.exception.ApiException;
import com.anxin.baseproject2.exception.ExceptionEngine;
import com.anxin.baseproject2.exception.ServerException;
import com.anxin.baseproject2.modle.enity.BaseHttpEnity;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

/**
 * 同意结果处理
 */
public abstract class RxObserver<T> implements Observer<T> {
    private Disposable disposable;

    @Override
    public void onError(Throwable e) {
        ApiException apiException = ExceptionEngine.handleException(e);
        onError(apiException);
    }


    @Override
    public void onComplete() {
        // 忽略操作，需要可覆写该方法
    }


    @Override
    public void onSubscribe(Disposable d) {
        this.disposable=d;
    }

    @Override
    public void onNext(T t) {
        if(t instanceof BaseHttpEnity){
            // 判断是否请求错误，出错直接转到onError()
            BaseHttpEnity enity= (BaseHttpEnity) t;
            if(enity.result_code ==0){
                onSuccess(t);
            }else{
                throw  new ServerException(enity.result_code,enity.result_msg);
            }
        }else if(t instanceof ResponseBody){
            onSuccess(t);
        }
    }


    public void dispose(){
        if(this.disposable!=null){
            if(!this.disposable.isDisposed()){
                this.disposable.dispose();
            }
        }
    }

    /**
     * 请求成功回调
     * @param t 最终响应结果
     */
    public abstract void onSuccess(T t);

    public abstract void onError(ApiException ex);
}